package org.wishwork.api.product.shop.query;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.product.shop.ShopProductApi;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 店铺商品资料查询
 * @author: WangYX
 * @create: 2022-04-11 14:37
 * @Version: 1.0.0
 **/

public class ShopProductQueryApi extends Api<List<ShopProductQueryResponse>, ShopProductQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(ShopProductQueryApi.class);

    private Context context;

    public ShopProductQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(ShopProductQueryRequest shopProductQueryRequest) throws Exception {
        String url = "/open/skumap/query";
        Map<String, Object> params = new HashMap<>();
        if (StrUtil.isNotEmpty(shopProductQueryRequest.getSkuIds())) {
            params.put("sku_ids", shopProductQueryRequest.getSkuIds());
        }
        if (shopProductQueryRequest.getShopId() != null) {
            params.put("shop_id", shopProductQueryRequest.getShopId());
        }
        return HttpHelper.sendRequest(shopProductQueryRequest, params, url);
    }

    @Override
    protected List<ShopProductQueryResponse> process(JSONObject data, ShopProductQueryRequest shopProductQueryRequest) throws Exception {

        JSONArray datas = data.getJSONArray("datas");
        List<ShopProductQueryResponse> shopProductQueryResponses = datas.toJavaList(ShopProductQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = shopProductQueryRequest.getPageIndex();
            ShopProductQueryRequest build = shopProductQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<ShopProductQueryResponse> business = business(build);
            shopProductQueryResponses.addAll(business);
        }
        return shopProductQueryResponses;
    }
}
